package com.central.apps.handler.contract;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.util.DateUtils;
import com.central.app.entity.TBFile;
import com.central.app.service.CheckConNodeService;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ConreviewHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Resource
    private CheckConNodeService checkConNodeService;

    @Autowired
    private ConapplicationHandler conapplicationHandler;
    @Autowired
    private ConUtil conUtil;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        //判断是否添加了评审组成员或者专家组成员
        if (flowNode.getId().equals("approal2")) {
            List<Map<String, Object>> list3 = handlerService.findBySql("select isonline ,conid from gq_conreviews where id = " + id);
            if ("是".equals(list3.get(0).get("isonline"))) {
                boolean res = isSetPersons(app, id);
                if (!res) {
                    return "选择线上评审后，需要添加评审组成员信息再提交审批";
                }
                //提交申请后就添加到会签表中
//                if ("是".equals(list3.get(0).get("isonline"))) {
//                    setcountersigns(app, id,app);
//                }
                //1.查询评审组成员
                //List<Map<String, Object>> list = handlerService.findBySql("select username from gq_reviewmember where conid = " + id);
                //2.专家组成员
//                List<Map<String, Object>> list2 = handlerService.findBySql("select username from gq_expertgroup where conid = " + id);
//                // StringBuffer names = new StringBuffer();
//                if (CollectionUtils.isEmpty(list2)) {
//                    return "选择线上评审后，需要添加评审组成员信息在提交审批";
//                }
            }
        }


        //---------------------合同评审 审批通过后----------------------------
        //如果进行会签评审，将审批意见添加到对应的列表中
//            if("countersign".equals(flowNode.getId())){
//
//                LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
//                String username = loginAppUser.getUsername();//审批人
//                String opinion = op.getOpinion().replace("<p>","").replace("</p>","");//审批意见
//                //更新评审组成员
//                String sql = "update gq_reviewmember set revcomments ='"+opinion+"' where conid = "+id +" and username = '"+username+"'";
//                handlerService.updateBySql(sql);
//                //更新专家组信息
//                String sql1 = "update gq_expertgroup set revcomments ='"+opinion+"' where conid = "+id +" and username = '"+username+"'";
//                handlerService.updateBySql(sql1);
//
//            }
        //审批通过后
        if (flowNode.getId().equals("approal")) {
            boolean flag = op.isFlag();
            if (flag) {
                String sql = "select * from  gq_conreviews where id = " + id;
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                if (CollectionUtils.isNotEmpty(list)) {
                    String ispublicity = (String) list.get(0).get("ispublicity");
                    String conid = (String) list.get(0).get("conid");
                    //将合同申请中的合同状态改为待签定,合同金额也修改一下,框架合同剩余金额
                    String upd1 = "update gq_conapplication set constatus ='待签订',untotalprice= "+list.get(0).get("reviewmoney")+"  where conid = '" + conid + "'";
                    handlerService.updateBySql(upd1);
                    String upd2 = "update gq_conreviews set constatus ='待签订'  where conid = '" + conid + "'";
                    handlerService.updateBySql(upd2);
                    //将合同申请中的合同状态改为待签定,合同金额也修改一下,对方单位名称也需要修改一下，框架合同剩余金额
                    String upd3 = "update gq_conaccount set constatus ='待签订' ,totalprice = " + list.get(0).get("reviewmoney") + ",untotalprice="+list.get(0).get("reviewmoney")+", oppcompany= '" + list.get(0).get("secondname") + "',conname='" + list.get(0).get("conname") + "'   where conid = '" + conid + "'";
                    handlerService.updateBySql(upd3);
                    //将上传的文件插入到合同台账的
                    fileSynUtilService.insertFiles(app, id, Integer.valueOf(conid), null);
                    //流程归档
                    fileSynUtilService.processarc(app, id + "", "合同评审", (String) list.get(0).get("concode"), (String) list.get(0).get("conname"));
                    //判断订单信息是否可见
                    //判断订单是否显示，如果是简易合同，评审完后显示，否则，不显示
                    if("是".equals(list.get(0).get("isconsign"))){
                        handlerService.updateBySql("update gq_po set isshow ='是' where conid = "+conid);
                    }

                }
            }
        }

        //会签提交前，验证有没有填写评审意见
        //会签审批通过后，把会签意见同步到意见历史中
        //日志打印
        System.out.println("驳回后日志打印，查看状态==================" + flowNode.getId());
        if ("countersign".equals(flowNode.getId())) {
            boolean res = isOpinion(app, id);
            if (!res) {
                return "请填写审批意见再提交";
            }
            //setRevcoments(app, id);
            //提交会见意见后，置空主表评审意见
            setnullrevcomments(id, "gq_conreviews");
        }

//        if ("approal1".equals(flowNode.getId())) {
//            List<Map<String, Object>> list3 = handlerService.findBySql("select isonline,conid from gq_conreviews where id = " + id);
//            //String conid = (String) list3.get(0).get("conid");
//            if ("是".equals(list3.get(0).get("isonline"))) {
//                setcountersigns(app, id);
//            }
//        }

        return super.beforeExcuteFlow(app, id, flowNode, op);
    }


    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {

        //审批后，把责任人赋值过去
        String executors = conUtil.getUsersInfo(app, id);
        handlerService.updateBySql(" update gq_conreviews set executors ='" + executors + "' where id =" + id);
    }

    @Override
    public void afterTransfer(String app, Long id) throws Exception {
        //审批后，把责任人赋值过去
        String executors = conUtil.getUsersInfo(app, id);
        handlerService.updateBySql(" update gq_conreviews set executors ='" + executors + "' where id =" + id);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {

        //将合同申请里的合同文本，添加到合同评审，写一个公共方法，from to
        //先删除，在添加
        if ("gq_conreviews".equals(objName)) {
            Long toId = MapUtils.getLong(data, "id");
//            List<Map<String, Object>> list = handlerService.findBySql("select conid,applyid from gq_conreviews where id = " + toId);
//            //String sql = "select id from gq_conapplication where conid = "+list.get(0).get("conid");
//            Long fromId = MapUtils.getLong(data, "applyid");//合同申请主表id
//            fileremove("conapplicationApp", fromId, app, toId, true, "pro");

            List<Map<String, Object>> list3 = handlerService.findBySql("select isonline ,conid,revcomments from gq_conreviews where id = " + toId);
            if ("是".equals(list3.get(0).get("isonline"))) {
                //提交申请后就添加到会签表中
                if ("是".equals(list3.get(0).get("isonline"))) {
                    setcountersigns(app, toId, app);
                }
                //1.查询评审组成员
                //List<Map<String, Object>> list = handlerService.findBySql("select username from gq_reviewmember where conid = " + id);
                //2.专家组成员
//                List<Map<String, Object>> list2 = handlerService.findBySql("select username from gq_expertgroup where conid = " + id);
//                // StringBuffer names = new StringBuffer();
//                if (CollectionUtils.isEmpty(list2)) {
//                    return "选择线上评审后，需要添加评审组成员信息在提交审批";
//                }
            }
            //将主表中的评审意见添加到对应的子表评审意见位置。
            moverevcomments(data);
//            String revcomments = MapUtils.getString(data,"revcomments");
//            if(ToolUtil.isNotEmpty(revcomments)){
//                LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
//                String username = loginAppUser.getUsername();
//                handlerService.updateBySql("update gq_expertgroup set revcomments = '"+revcomments+"' where conid = '"+list3.get(0).get("id")+"' and username = '"+username+"'");
//            }


        }
        //统计对方单位名称
        if ("gq_coordinationinfo".equals(objName)) {
            long conid = MapUtils.getLongValue(data, "conid");
            conapplicationHandler.setTwos(conid, "gq_conreviews");
        }

//汇总合同评审中物料数据到主表
        if ("gq_poline".equals(objName)) {
            Map<String, Object> map = handlerService.findOneBySql("select sum(totalcost) as totalcosts  from gq_poline where conid =" + data.get("conid"));
            if (map != null) {
                String totalprice = MapUtils.getString(map, "totalcosts");
                handlerService.updateBySql("update gq_conreviews set reviewmoney =" + totalprice + "  where conid =" + data.get("conid"));
            }
        }

        //获取合同申请中供方单位子表中的数据，汇总到乙方名称中 关联关系pid=:id
//        String sql = "select  companyname from gq_coordinationinfo where pid = "+fromId;
//        List<Map<String,Object>> list2= handlerService.findBySql(sql);
//        StringBuffer sb = new StringBuffer();
//        String companynames="";
//        if(CollectionUtils.isNotEmpty(list2)){
//            for (Map<String, Object> stringObjectMap : list2) {
//                sb.append(",").append(stringObjectMap.get("companyname"));
//            }
//            companynames = sb.toString().replaceFirst(",","");
//            String upd = "update gq_conreviews set secondname ='"+companynames+"' where id = "+toId;
//            handlerService.updateBySql(upd);
//        }


    }

    //置空主表评审意见
    public void setnullrevcomments(long id, String tableName) {
        handlerService.updateBySql("update " + tableName + " set revcomments='' where id = " + id);
    }

    //将主表中的评审意见添加到对应的子表评审意见位置。
    public void moverevcomments(Map<String, Object> data) {

        String revcomments = MapUtils.getString(data, "revcomments");
        if (ToolUtil.isNotEmpty(revcomments)) {
            LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
            //String username = loginAppUser.getUsername();
            int usercode = loginAppUser.getField10();//获取当前登录人
            handlerService.updateBySql("update gq_expertgroup set revcomments = '" + revcomments + "' where conid = '" + data.get("id") + "' and username = '" + usercode + "'");
        }
    }

    //是否直接查询多个
    public void fileremove(String fromApp, long fromId, String toApp, long toId, boolean isLike, String prefix, boolean isdel) {
        //
        if (isdel) {
            String del = "delete from tb_file where appname = '" + toApp + "' and recordid = '" + toId + "' ";
            handlerService.updateBySql(del);
        }
        if (isLike) {
            toApp = prefix + toApp;
            List<TBFile> tbFiles = checkConNodeService.selectLikeFiles(fromApp, fromId);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(tbFiles)) {
                for (TBFile tbFile : tbFiles) {
                    if (fromApp.equals(tbFile.getAppname())) {
                        continue;
                    }
                    tbFile.setFileid(null);
                    tbFile.setAppname(toApp);
                    tbFile.setRecordid(toId);
                    checkConNodeService.insertConfiles(tbFile);
                }
            }
        } else {
//            String del = "delete from tb_file where appname = '" + toApp + "' and recordid = '" + toId + "' ";
//            handlerService.updateBySql(del);
            List<TBFile> tbFiles = checkConNodeService.selectFiles(fromApp, fromId);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(tbFiles)) {
                for (TBFile tbFile : tbFiles) {
                    tbFile.setFileid(null);
                    tbFile.setAppname(toApp);
                    tbFile.setRecordid(toId);
                    checkConNodeService.insertConfiles(tbFile);
                }
            }
        }

    }

    //如果是线上评审，需要增加评审人员
    public boolean isSetPersons(String app, long id) {
        List<Map<String, Object>> list2 = handlerService.findBySql("select username from gq_expertgroup where conid = " + id + " and appname = '" + app + "'");
        // StringBuffer names = new StringBuffer();
        boolean res = true;
        if (CollectionUtils.isEmpty(list2)) {
            res = false;
        }
        return res;
    }

    public void setRevcoments(String appname, long id) {
        //String sql2 = "select conid from  gq_conreviews where id = " + id;
//            List<Map<String, Object>> list2 = handlerService.findBySql(sql2);
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
        int usercode = loginAppUser.getField10();//获取当前登录人
        String sql = "select revcomments,revcommentshis,id from  gq_expertgroup where conid = " + id + " and username = " + usercode + " and appname = '" + appname + "'";

        List<Map<String, Object>> list = handlerService.findBySql(sql);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> stringObjectMap : list) {
                String revcommentshis = (String) stringObjectMap.get("revcommentshis");
                String revcomments = (String) stringObjectMap.get("revcomments");
                if (ToolUtil.isNotEmpty(revcomments)) {
                    revcommentshis += "\r\n";
                    String date = "";
                    date = DateUtils.getCurrentString();
                    revcommentshis = revcommentshis + revcomments + ",时间：" + date + ";";
                    handlerService.updateBySql("update gq_expertgroup set revcommentshis= '" + revcommentshis + "',revcomments='' where id = " + stringObjectMap.get("id"));
                }

            }

        }
    }

    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        //驳回后同步评审意见到历史评审意见
        setAllRevcoments(app, id);
    }

    //驳回后，批量将评审意见移动到历史意见里边
    public void setAllRevcoments(String appname, long id) {
        String sql = "select revcomments,revcommentshis,id from  gq_expertgroup where conid = " + id + " and appname = '" + appname + "'";
        List<Map<String, Object>> list = handlerService.findBySql(sql);
        if (CollectionUtils.isNotEmpty(list)) {
            for (Map<String, Object> stringObjectMap : list) {
                String revcommentshis = (String) stringObjectMap.get("revcommentshis");
                String revcomments = (String) stringObjectMap.get("revcomments");
                if (ToolUtil.isNotEmpty(revcomments)) {
                    revcommentshis += "\r\n";
                    String date = "";
                    date = DateUtils.getCurrentString();
                    revcommentshis = revcommentshis + revcomments + ",时间：" + date + ";";
                    handlerService.updateBySql("update gq_expertgroup set revcommentshis= '" + revcommentshis + "',revcomments='' where id = " + stringObjectMap.get("id"));
                }

            }

        }
    }

    //将表格中的人员信息添加到会签表中
    public void setcountersigns(String app, long id, String appname) {
        List<Map<String, Object>> list2 = handlerService.findBySql("select username,persontype from gq_expertgroup where conid = " + id + " and appname ='" + appname + "'");
        StringBuffer names = new StringBuffer();

        if (CollectionUtils.isNotEmpty(list2)) {
            for (Map<String, Object> stringObjectMap : list2) {
                String psrsontype = MapUtils.getString(stringObjectMap, "persontype");
                String username = MapUtils.getString(stringObjectMap, "username");
                username = getUserName(username);//根据用户编号获取用户登录名
                names.append(",").append(username);

            }
            //System.out.println("评审组人员=====" + names.toString());
            //先删除，在添加
            handlerService.updateBySql("delete from biz_flow_countersign where app='" + app + "' and biz_id = " + id);
            String sql = "INSERT INTO biz_flow_countersign (app, biz_id, node_id, countersign) VALUES ( '" + app + "', '" + id + "', 'approal2', '" + names.toString().replaceFirst(",", "") + "')";
            handlerService.updateBySql(sql);
        }


    }

    public String getUserName(String userid) {
        String username = "";
        List<Map<String, Object>> list = handlerService.findBySql("select username from sys_user where field10=" + userid);
        username = MapUtils.getString(list.get(0), "username");
        return username;
    }

    //判断是否填写了评审意见
    public boolean isOpinion(String appName, long id) {
        boolean res = true;
        LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
        int usercode = loginAppUser.getField10();//获取当前登录人
        //查询会签人是否填写了会签意见
        String sql = "select revcomments from  gq_expertgroup where conid = " + id + " and appname = '" + appName + "' and username ='" + usercode + "'";
        List<Map<String, Object>> list = handlerService.findBySql(sql);
        if (CollectionUtils.isEmpty(list) || ToolUtil.isEmpty(list.get(0)) || ToolUtil.isEmpty(list.get(0).get("revcomments"))) {
            res = false;
        }
        return res;
    }
}
